package com.xingzhe.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xingzhe.media.mapper.MediaFilesMapper;
import com.xingzhe.media.mapper.MediaProcessHistoryMapper;
import com.xingzhe.media.mapper.MediaProcessMapper;
import com.xingzhe.media.model.po.MediaFiles;
import com.xingzhe.media.model.po.MediaProcess;
import com.xingzhe.media.model.po.MediaProcessHistory;
import com.xingzhe.media.service.MediaFileProcessService;
import groovy.util.logging.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * MediaFileProcessService接口的实现
 */
@Slf4j
@Service
public class MediaFileProcessServiceImpl implements MediaFileProcessService {
    @Resource
    MediaProcessMapper mediaProcessMapper;
    @Resource
    MediaFilesMapper mediaFilesMapper;
    @Resource
    MediaProcessHistoryMapper mediaProcessHistoryMapper;
    @Override
    public List<MediaProcess> getMediaProcessList(int shardIndex, int shardTotal, int count) {
        return mediaProcessMapper.selectListByShardIndex(shardTotal, shardIndex, count);
    }

    @Override
    public boolean startTask(long id) {
        int result = mediaProcessMapper.startTask(id);
        return result > 0;
    }

    @Override
    public void saveProcessFinishStatus(Long taskId, String status, String fileId, String url, String errorMsg) {
        //要更新的任务
        MediaProcess mediaProcess = mediaProcessMapper.selectById(taskId);
        if (mediaProcess ==null){
            return; //frame=79684 fps=206 q=0.0 size=  194816kB time=01:13:47.16 bitrate= 360.5kbits/s dup=0 drop=53119 speed=11.4x
        }
        //如果任务执行失败
        if (status.equals("3")){
            //更新MediaProcess表的状态
            mediaProcess.setStatus("3");
            mediaProcess.setFailCount(mediaProcess.getFailCount()+1);//失败次数加一
            mediaProcess.setErrormsg(errorMsg);
            mediaProcessMapper.updateById(mediaProcess);
            return;
        }


        //如果任务成功
        //更新media_file表中的url
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileId);
        mediaFiles.setUrl(url);
        mediaFilesMapper.updateById(mediaFiles);

        //更新MediaProcess表的状态
        mediaProcess.setUrl(url);
        mediaProcess.setStatus("2");
        mediaProcess.setFinishDate(LocalDateTime.now());
        mediaProcessMapper.updateById(mediaProcess);
        //将MediaProcess表记录插入到MediaProcessHistory表
        MediaProcessHistory mediaProcessHistory = new MediaProcessHistory();
        BeanUtils.copyProperties(mediaProcess,mediaProcessHistory);
        mediaProcessHistoryMapper.updateById(mediaProcessHistory);

        //从MediaProcess删除当前任务
        mediaProcessMapper.deleteById(taskId);
    }
}
